package com.ww.springboot.boot.javabase.stream.groupingby;

import com.ww.springboot.boot.cyclic.A;
import lombok.Data;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2024-02-19 11:31
 */
public class GroupingByDemo1 {

    public static void main(String[] args) {
        List<GroupBy> list = new ArrayList<>();
        list.add(new GroupBy("1", 1));
        list.add(new GroupBy("1", 2));
        list.add(new GroupBy("3", 5));
        list.add(new GroupBy("3", 6));
        list.add(new GroupBy("2", 4));
        list.add(new GroupBy("4", 4));

        System.out.println("单字段分组：" + list.stream().collect(Collectors.groupingBy(GroupBy::getAge)));
        System.out.println("单字段分组：" + list.stream().collect(Collectors.groupingBy(GroupBy::getName)));

        System.out.println("单字段分组 value提取字段：" + list.stream().collect(Collectors.groupingBy(GroupBy::getAge, Collectors.mapping(GroupBy::getName, Collectors.toList()))));
        Map<Integer, Optional<GroupBy>> map = list.stream().collect(Collectors.groupingBy(GroupBy::getAge, Collectors.maxBy(Comparator.comparing(GroupBy::getName))));
        System.out.println("单字段分组 排序取最大值：" + map);


        LinkedHashMap<Integer, List<String>> sortMap = list.stream().collect(Collectors.groupingBy(GroupBy::getAge, LinkedHashMap::new, Collectors.mapping(GroupBy::getName, Collectors.toList())));
        System.out.println("分组后保留原有的顺序: " + sortMap);
        Map<Integer, Integer> sumMap = list.stream().collect(Collectors.groupingBy(GroupBy::getAge, Collectors.summingInt(GroupBy::getAge)));
        System.out.println("分组后统计: " + sumMap);

        Map<Integer, Map<String, List<GroupBy>>> doubleGroup = list.stream().collect(Collectors.groupingBy(GroupBy::getAge, Collectors.groupingBy(GroupBy::getName)));
        System.out.println("分组后再分组: " + doubleGroup);

        Map<Integer, List<String>> listMap = list.stream().collect(Collectors.groupingBy(GroupBy::getAge, Collectors.collectingAndThen(Collectors.toList(), s -> s.stream().map(GroupBy::getName).collect(Collectors.toList()))));
        System.out.println("分组后提取字段：" + listMap);

        Map<Integer, Long> longMap = list.stream().collect(Collectors.groupingBy(GroupBy::getAge, Collectors.collectingAndThen(Collectors.toList(), s -> s.stream().map(GroupBy::getName).distinct().count())));
        System.out.println("分组后提取字段并去重统计：" + longMap);
    }


    @Data
    static class GroupBy {

        public GroupBy(String name, int age) {
            this.name = name;
            this.age = age;
        }

        private String name;
        private int age;

        @Override
        public String toString() {
            return name + " - " + age;
        }
    }
}
